'use client'
import React, { useEffect, useState } from 'react';
import { Space, Table, Radio, Button, Modal, Form, Input, Row, Col } from 'antd';
import type { TableProps, FormProps } from 'antd';
import { EditOutlined, VerticalAlignTopOutlined, DeleteOutlined, ContainerOutlined, FormOutlined, ZoomOutOutlined, RedoOutlined, VerticalAlignBottomOutlined, RetweetOutlined } from '@ant-design/icons';

// 定义数据类型
interface DataType {
  id: number,
  shangji: string,
  title: string,
  jieduan: string,
  num: string,
  sprice: string,
  time: string,
  day: number,
  name: string;
}

export default function Home() {
  const rowSelection: TableProps<DataType>['rowSelection'] = {
    onChange: (selectedRowKeys: React.Key[], selectedRows: DataType[]) => {
      console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
    },
    getCheckboxProps: (record: DataType) => ({
      disabled: record.name === 'Disabled User', // Column configuration not to be checked
      name: record.name,
    }),
  };

  const [searchList, setSearchList] = useState<any>([])
  const [list, setList] = useState([
    {
      id: 1,
      shangji: "商机标题",
      title: "深圳市亿恩科技有限公司",
      jieduan: "异步洽谈",
      num: "10条",
      sprice: "￥10,000.00",
      time: 1752689523547,
      day: 30
    },
    {
      id: 2,
      shangji: "商机标题",
      title: "深圳市亿恩科技有限公司",
      jieduan: "初步洽谈",
      num: "10条",
      sprice: "￥10,000.00",
      time: 1752689523547,
      day: 30
    },
    {
      id: 3,
      shangji: "商机标题",
      title: "深圳市亿恩科技有限公司",
      jieduan: "初步洽谈",
      num: "10条",
      sprice: "￥10,000.00",
      time: 1752689523547,
      day: 30
    },
    {
      id: 4,
      shangji: "商机标题",
      title: "深圳市亿恩科技有限公司",
      jieduan: "初步洽谈",
      num: "10条",
      sprice: "￥10,000.00",
      time: 1752689523547,
      day: 30
    },
    {
      id: 5,
      shangji: "111标题",
      title: "深圳市亿恩科技有限公司",
      jieduan: "初步洽谈",
      num: "9条",
      sprice: "￥10,000.00",
      time: 1752689523547,
      day: 30
    },
  ])
  const columns: TableProps<DataType>['columns'] = [
    {
      title: '商机标题',
      dataIndex: 'shangji',
    },
    {
      title: '关联客户',
      dataIndex: 'title',
    },
    {
      title: '商机阶段',
      dataIndex: 'jieduan',
    },
    {
      title: '报价记录',
      dataIndex: 'num',
    },
    {
      title: '报价总金额',
      dataIndex: 'sprice',
    },
    {
      title: '最后跟进',
      dataIndex: 'time',
    },
    {
      title: '未跟进天数',
      dataIndex: 'day',
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle" style={{ color: 'blue' }}>
          <a onClick={() => {
            showModal()
            setTitle('编辑')
            form.setFieldsValue(record);
            setEditingId(record.id);
          }}><EditOutlined />编辑</a>
          <a onClick={() => {
            let newlist = list.filter(item => item.id !== record.id)
            newlist.unshift(record)
            setSearchList(newlist)
          }}><VerticalAlignTopOutlined />置顶</a>
          <a onClick={() => {
            setSearchList(prevList => prevList.filter(item => item.id !== record.id));
          }}><DeleteOutlined />删除</a>
        </Space>
      ),
    },
  ];

  // 控制标头标识 显示状态 以及正在编辑的id
  const [title, setTitle] = useState('添加')
  const [selectionType, setSelectionType] = useState<'checkbox' | 'radio'>('checkbox');

  const [isModalOpen, setIsModalOpen] = useState(false);
  const [editingId, setEditingId] = useState<number | null>(null);

  const showModal = () => {
    setIsModalOpen(true);
  };

  const handleCancel = () => {
    setIsModalOpen(false);
    form.resetFields();
    setEditingId(null);
  };

  const [form] = Form.useForm();

  const handleAddOrEdit = () => {
    form.validateFields().then((values) => {
      if (editingId) {
        // 编辑
        setSearchList(prevList =>
          prevList.map(item =>
            item.id === editingId ? { ...item, ...values } : item
          )
        )
      } else {
        const newId = list.length > 0 ? Math.max(...list.map(item => item.id)) + 1 : 1;
        const newItem = {
          id: newId,
          ...values
        };
        setSearchList([newItem, ...list]);
      }
      // 关闭弹窗
      setIsModalOpen(false);
      form.resetFields();
      setEditingId(null)
    }).catch((errorInfo) => {
      console.log('Failed:', errorInfo);
    });
  };

  const onFinish: FormProps<any>['onFinish'] = (values) => {
    if (values.shangji != '') {
      setSearchList(list.filter(item => item.shangji.includes(values.shangji)))
    }
    if (values.title) {
      setSearchList(list.filter(item => item.title.includes(values.title)))
    }
    if (values.jieduan) {
      setSearchList(list.filter(item => item.jieduan.includes(values.jieduan)))
    }

  };

  useEffect(() => {
    setSearchList(list)
  }, [])
  return (
    <div>
      {/* 搜索表单 */}
      <Form layout="inline" onFinish={onFinish} form={form}>
        <Space>
          <Form.Item name="shangji" label="商机标题">
            <Input />
          </Form.Item>
          <Form.Item name="title" label="关联客户">
            <Input />
          </Form.Item>
          <Form.Item name="jieduan" label="商机阶段">
            <Input />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType='submit'><ZoomOutOutlined />搜索</Button>
          </Form.Item>
          <Form.Item>
            <Button onClick={() => {
              form.resetFields()
              setSearchList(list)
            }}><RedoOutlined />重置</Button>
          </Form.Item>
          <Form.Item>
            <Button><VerticalAlignTopOutlined />高级搜索</Button>
          </Form.Item>
        </Space>
      </Form><br />

      {/* 添加弹窗 */}
      <Button type="primary" onClick={() => {
        showModal();
        setTitle('添加');
        form.resetFields();
        setEditingId(null);
      }}>
        添加
      </Button>&nbsp;&nbsp;&nbsp;
      <Button><VerticalAlignTopOutlined />导入</Button>&nbsp;&nbsp;&nbsp;
      <Button><VerticalAlignBottomOutlined />导出</Button>&nbsp;&nbsp;&nbsp;
      <Button><RetweetOutlined />转移商机</Button>&nbsp;&nbsp;&nbsp;
      <Button><FormOutlined />添加协作</Button>&nbsp;&nbsp;&nbsp;
      <Button><ContainerOutlined />发送短信</Button>
      <br />
      <Modal footer={null}
        title={title}
        open={isModalOpen}
        onCancel={handleCancel}
        onOk={handleAddOrEdit}
      >
        {/* 添加表单 */}
        <Form
          form={form}
          layout="vertical"
        >
          <Form.Item
            name="shangji"
            label="商机标题"
            rules={[{ required: true, message: '请输入商机标题' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="title"
            label="关联客户"
            rules={[{ required: true, message: '请输入关联客户' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="jieduan"
            label="商机阶段"
            rules={[{ required: true, message: '请输入商机阶段' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="num"
            label="报价记录"
            rules={[{ required: true, message: '请输入报价记录' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="sprice"
            label="报价总金额"
            rules={[{ required: true, message: '请输入报价总金额' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="time"
            label="最后跟进"
            rules={[{ required: true, message: '请输入最后跟进时间' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="day"
            label="未跟进天数"
            rules={[{ required: true, message: '请输入未跟进天数' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
          >
            <Button onClick={handleAddOrEdit}>确定</Button>
          </Form.Item>
        </Form>
      </Modal>

      <Radio.Group onChange={(e) => setSelectionType(e.target.value)} value={selectionType}></Radio.Group>
      <Table<DataType> columns={columns} rowSelection={{ type: selectionType, ...rowSelection }} dataSource={searchList} rowKey='id' />
    </div>
  );
}
